<?php


namespace App\Http\Swoole;


use App\Models\Machine;
use App\Services\RedisTable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Swoole\Websocket\Frame;
use SwooleTW\Http\Websocket\Facades\Websocket;
use SwooleTW\Http\Websocket\HandlerContract;

class WebsocketHandler implements HandlerContract
{
    public function onOpen($fd, Request $request)
    {
        $validator = Validator::make($request->all(),[
            'role'  => 'required|string',
            'token' => 'required',
        ]);

        $data = $validator->validated();

        if ($validator->fails()){

            Websocket::emit('error',['info'=>'参数错误','data'=>$validator->errors()]);
            return false;
        }

        $auth = auth($data['role']);
        $auth->factory()->setToken($data['token']);

        if ($auth->check()){

            switch ($data['role']){
                case 'express':

                    Websocket::join('express');
                    RedisTable::SwooleMachineSave($auth->id(),$fd);
                    Websocket::loginUsing($auth->user());
                    if ($flag = Machine::find(Websocket::getUserId())){
                        $flag->is_online = 1;
                        $flag->save();
                        Websocket::emit('open',['info'=>'欢迎：'.Websocket::getUserId()]);
                    }

                    break;
            }

        }else{

            Websocket::emit('error',['info'=>'用户验证失败','data'=>[]]);
            Websocket::close($fd);
        }
    }

    public function onMessage(Frame $frame)
    {
        Websocket::emit('message',['msg'=>'接收数据','data'=>$frame]);
    }

    public function onClose($fd, $reactorId)
    {
        Log::channel('single')->debug('链接关闭：'.$fd);
    }
}
